package com.super8.super8newtv;

import static com.super8.super8newtv.utils.Utils.getStringDate;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stx.xhb.xbanner.XBanner;
import com.super8.super8newtv.adapter.HotelPriceAdapter;
import com.super8.super8newtv.api.Api;
import com.super8.super8newtv.api.ApiContract;
import com.super8.super8newtv.api.ApiError;
import com.super8.super8newtv.api.ApiService;
import com.super8.super8newtv.api.parser.ResponseBeanParser;
import com.super8.super8newtv.api.parser.TokenBeanParser;
import com.super8.super8newtv.bean.FullScreenBean;
import com.super8.super8newtv.bean.HotelpriceBean;
import com.super8.super8newtv.bean.ImagesBean;
import com.super8.super8newtv.bean.MediafileBean;
import com.super8.super8newtv.bean.NoticeBean;
import com.super8.super8newtv.bean.ResponseBean;
import com.super8.super8newtv.bean.TokenBean;
import com.super8.super8newtv.bean.UpdateBean;
import com.super8.super8newtv.bean.WeatherCityBean;
import com.super8.super8newtv.utils.CacheUtil;
import com.super8.super8newtv.utils.DownloadUtil;
import com.super8.super8newtv.utils.FileUtil;
import com.super8.super8newtv.utils.LogUtils;
import com.super8.super8newtv.utils.MyTimeTask;
import com.super8.super8newtv.utils.Utils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;

/*
 * 电子房价牌-横屏版页面
 */
public class HorizontalActivity extends Activity {

    @BindView(R.id.lin_parent)
    LinearLayout lin_parent;//半屏布局
    @BindView(R.id.rl_left)
    RelativeLayout rl_left;//左半屏布局(酒店房价 时间 天气信息)
    @BindView(R.id.rl_right)
    RelativeLayout rl_right;//右半屏布局(视频图片)

    //日期 时间
    @BindViews({R.id.tv_now_time, R.id.tv_now_date})
    List<TextView> tvDateTimeList;//日期 时间v相关view

    //天气
    @BindViews({R.id.ll_today_tem_iv, R.id.ll_today_tem})
    List<LinearLayout> llTodayList;//今天天气布局
    @BindViews({R.id.ll_tom_tem_iv, R.id.ll_tom_tem})
    List<LinearLayout> llTomList;//明天天气布局

    @BindViews({R.id.iv_today_weather, R.id.iv_tom_weather})
    List<ImageView> ivWeatherList;//天气图片view
    @BindViews({R.id.tv_today_tem_high, R.id.tv_today_low, R.id.tv_today_weather_type})
    List<TextView> tvTodayTemList;//当天温度 相关view
    @BindViews({R.id.tv_tom_tem_high, R.id.tv_tom_low, R.id.tv_tom_weather_type})
    List<TextView> tvTomTemList;//明天温度 相关view
    @BindView(R.id.recycler_view)
    AutoPollRecyclerView recyclerView;//房价布局

    @BindViews({R.id.tv_hotel_name, R.id.tv_marquee, R.id.tv_hotel_notice})
    List<TextView> tvHotelInfoList;//酒店名称,总部通告, 酒店公告 相关view
    @BindView(R.id.iv_hotel_image)
    ImageView ivHotelImage;//酒店类型图标（1.0 2.0）
    @BindView(R.id.xbanner)
    XBanner mXBanner;//图片

    @BindView(R.id.video_view_right)
    VideoView video_view_right;//半屏_视频

    private List<HotelpriceBean> hotelPriceDataList = new ArrayList<>();
    private List<HotelpriceBean> tempPriceDataList;//
    private HotelPriceAdapter hotelPriceAdapter;

    private List<ImagesBean> imgList;//轮播图片集
    private List<String> imgUrlList;//轮播图片URL集
    private List<String> videoList;//视频集
    List<String> lsDownFileName;//下载文件信息
    List<String> lsDownloadIamge;//下载图片信息   先获取本地图片是否


    private List<ImagesBean> lsFullImg;//轮播图片集
    private List<String> lsFullImgUrl;//轮播图片URL集
    List<String> lsFullVideoName;//下载文件信息
    Map<String, FullScreenBean> fullScreenShowTime;

    List<MediafileBean> lshalfScreenData, lsfullScreenData;
    private int currentPosition = 0;

    private TokenBean tokenBean;//token信息
    List<WeatherCityBean> lsWeather;//城市天气
    private List<NoticeBean> lsNoticeBean;//通知信息

    private String access_token;
    private static final String TAG = "HorizontalActivity";

    static class HomeHandler extends Handler {
        private final WeakReference<HorizontalActivity> homeFragmentWeakReference;

        HomeHandler(HorizontalActivity mainActivity) {
            homeFragmentWeakReference = new WeakReference<HorizontalActivity>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final HorizontalActivity activity = homeFragmentWeakReference.get();
            if (activity == null || activity.isFinishing()) {
                removeCallbacksAndMessages(null);
                return;
            }

        }
    }

    MyTimeTask myTimeTask;
    @SuppressLint("HandlerLeak")
    private HorizontalActivity.HomeHandler mHandler = new HorizontalActivity.HomeHandler(HorizontalActivity.this) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:  //酒店名称 以及 公告
                    if (!lsNoticeBean.isEmpty()) {
                        //酒店名称
                        tvHotelInfoList.get(0).setText(lsNoticeBean.get(0).getHotelName() + "");//酒店名称
                        //酒店类型
                        if (lsNoticeBean.get(0).getHotelBrand() == 2 || lsNoticeBean.get(0).getHotelBrand() == 4)
                            ivHotelImage.setImageResource(R.mipmap.logo_su8_2);
                        else
                            ivHotelImage.setImageResource(R.mipmap.logo_su8_1);
                        //总部通过
                        String temp = lsNoticeBean.get(0).getNotice();
                        if (temp.length() / 10 < 7) {
                            for (int i = 0; i < 7 - (temp.length() / 10); i++)
                                temp += "    " + temp;
                        }
                        tvHotelInfoList.get(1).setText(temp + "");//总部通过
                        //酒店公告
                        if (!TextUtils.isEmpty(lsNoticeBean.get(0).getHotelNotice())) {
                            tvHotelInfoList.get(2).setVisibility(View.VISIBLE);
                            tvHotelInfoList.get(2).setText("酒店公告：" + lsNoticeBean.get(0).getHotelNotice());
                        } else {
                            tvHotelInfoList.get(2).setVisibility(View.GONE); //隐藏酒店公告
                        }
                    }
                    break;
                case 2: //房价
                    hotelPriceDataList.clear();
                    hotelPriceDataList.addAll(tempPriceDataList);
                    if (tempPriceDataList.size() > 6)
                        hotelPriceAdapter.setDataNum(10);
                    hotelPriceAdapter.notifyDataSetChanged();
                    recyclerView.start();//开始循环滚动
                    break;
                case 30:
                    showHalfScreenData();//半屏展示
                    break;
                case 4://全屏数据获取
                    initMyTimeTask();
                    break;
                case 5://图片转换到视频播放
                    loadBanner(imgList, imgUrlList, videoList);
                    break;
                case 41:
                    String data = msg.getData().getString("showTimeName");
                    FullScreenBean fullScreenBean = new Gson().fromJson(data, FullScreenBean.class);
                    Intent intent = new Intent(HorizontalActivity.this, FullScreenActivity.class);
                    intent.putExtra("lsImg", new Gson().toJson(lsFullImg));
                    intent.putExtra("lsImgUrl", new Gson().toJson(lsFullImgUrl));
                    intent.putExtra("lsVideoName", new Gson().toJson(lsFullVideoName));
                    intent.putExtra("fullScreenBean", data);
                    startActivity(intent);
                    break;
                case 6:  //实时更新数据
                    String updateData = msg.getData().getString("updateData");
                    UpdateBean updateBean = new Gson().fromJson(updateData, UpdateBean.class);
                    if (updateBean != null) {
                        int notice = updateBean.getNotice();
                        int halfScreen = updateBean.getHalfScreen();
                        int fullScreen = updateBean.getFullScreen();
                        int prices = updateBean.getPrices();
                        if (notice == 1)
                            getNotices();//获取滚动字幕
                        if (halfScreen == 1)
                            getMediafiles();  //获取半屏广告
                        if (fullScreen == 1)
                            getFullScreenMediaFiles();  //获取全屏广告
                        if (prices == 1)
                            getHotelprice();  //获取酒店房型以及价钱
                    }
                    break;
                case 7:
                    String strMediafiles = msg.getData().getString("Mediafiles");
                    lshalfScreenData = new Gson().fromJson(strMediafiles, new TypeToken<List<MediafileBean>>() {
                    }.getType());//获取半屏数据
                    if (lshalfScreenData != null && lshalfScreenData.size() > 0)
                        showHalfScreenData(); //展示半屏
                    break;

                case 9:
                    String strFullScreenMediaFiles = msg.getData().getString("FullScreenMediaFiles");
                    lsfullScreenData = new Gson().fromJson(strFullScreenMediaFiles, new TypeToken<List<MediafileBean>>() {
                    }.getType());//获取全屏数据
                    initFullScreenData(); //初始全屏数据
                    break;

                case 500:  //当前时间更新
                    String substring = getStringDate().substring(11, 16);
                    tvDateTimeList.get(0).setText(substring + "");
                    break;
                case 501://当前日期 星期更新
                    String nowTime = Utils.getNowTime();
                    String currentWeek = Utils.dateToWeek(nowTime);
                    String month = Utils.getNowTime().substring(5, 7);
                    String day = Utils.getNowTime().substring(8, 10);
                    tvDateTimeList.get(1).setText(month + "月" + day + "日  " + currentWeek);//日期
                    break;
                case 8://获取天气(crs系统中)
//                    LogUtils.e("GetWeather", "lsWeather：" + new Gson().toJson(lsWeather));
                    setWeather(lsWeather.get(0).getWeather(), ivWeatherList.get(0));
                    tvTodayTemList.get(0).setText(lsWeather.get(0).getTemEnd() + "°");//当天最高
                    tvTodayTemList.get(1).setText(lsWeather.get(0).getTemStart() + "°");//当天最低
                    tvTodayTemList.get(2).setText(lsWeather.get(0).getWeather() + "");//当天天气
                    if (lsWeather.size() > 1) {
                        llTomList.get(0).setVisibility(View.VISIBLE);
                        llTomList.get(1).setVisibility(View.VISIBLE);
                        setWeather(lsWeather.get(1).getWeather(), ivWeatherList.get(1));
                        tvTomTemList.get(0).setText(lsWeather.get(1).getTemEnd() + "°");//明天最高
                        tvTomTemList.get(1).setText(lsWeather.get(1).getTemStart() + "°");//明天最低
                        tvTomTemList.get(2).setText(lsWeather.get(1).getWeather() + "");//明天天气
                    } else {
                        llTomList.get(0).setVisibility(View.GONE);
                        llTomList.get(1).setVisibility(View.GONE);
                    }
                    break;
                case -8:
                    llTodayList.get(0).setVisibility(View.GONE);
                    llTodayList.get(1).setVisibility(View.GONE);
                    llTomList.get(0).setVisibility(View.GONE);
                    llTomList.get(1).setVisibility(View.GONE);
                    break;
                case 20:
                    recyclerView.smoothScrollToPosition(0);
                    break;
                case 110:
                    getLoginToken();//刷新token失败
                    break;
                case 120:
                    //登录失败
                    Toast.makeText(HorizontalActivity.this, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(HorizontalActivity.this, MainActivity.class));
                    finish();
                    break;
                case 98:
                    //判断是否需要下载图片
                    if (imgUrlList != null && imgUrlList.size() > 0) {
                        for (int i = 0; i < imgUrlList.size(); i++) {
                            if (!lsDownloadIamge.contains(imgUrlList.get(i))) {
                                //开始下载
                                String tempImageUrl = imgUrlList.get(i);
                                String tempImageName = DownloadUtil.getUrlLastNameSuffix(tempImageUrl);
                                String printTxtPath = getApplicationContext().getFilesDir().getAbsolutePath();
                                if (!FileUtil.isFileExist(printTxtPath + "/image_cache/" + tempImageName)) {//文件是否存在
                                    String finalTempUrl = tempImageUrl;
                                    String finalTempVideoName = "super8_" + Utils.getNowHour() + "_" + tempImageName;
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            downFile(finalTempUrl, printTxtPath + "/image_cache/", finalTempVideoName, 2); //下载
                                        }
                                    }).start();
                                    break;
                                }
                            }
                        }
                    }
                    break;
                case 99: //图片下在完成
                    String temp = msg.getData().getString("imageName");
                    String imageName = temp.replace("super8_" + Utils.getNowHour() + "_", "");
                    String path = getApplicationContext().getFilesDir().getAbsolutePath() + "/image_cache/";
                    //把下载文件名称改正确
                    Utils.reNameFile(path + temp, path + imageName);
                    lsDownloadIamge.add(imageName);//图片下载成功
                    mHandler.sendEmptyMessage(98);//判断是否需要下载图片
                    break;
            }
        }
    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_horizontal);
        ButterKnife.bind(this);
        checkToken();//检测token
        initView();
        initData();
        initDonloadImage();
        initRunnable();//

    }

    //初始下载图片
    private void initDonloadImage() {
//        Utils.deleteDir(getApplicationContext().getCacheDir().getAbsolutePath() + "/image_cache");//图片删除
        lsDownloadIamge = new ArrayList<>();
        File dir = new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/image_cache");
        if (dir == null || !dir.exists() || !dir.isDirectory())
            return;

        for (File file : dir.listFiles()) {
            if (file.isFile())
                lsDownloadIamge.add(file.getName());
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        String nowTime = Utils.getNowTime();
        String currentWeek = Utils.dateToWeek(nowTime);
        String month = Utils.getNowTime().substring(5, 7);
        String day = Utils.getNowTime().substring(8, 10);
        tvDateTimeList.get(1).setText(month + "月" + day + "日  " + currentWeek);//日期
        String substring = getStringDate().substring(11, 16);
        tvDateTimeList.get(0).setText(substring + "");//时间
        //跑马灯效果必须加
        tvHotelInfoList.get(1).setSelected(true);//总部通告
        tvHotelInfoList.get(2).setSelected(true);//酒店通告
    }

    /**
     * 初始化数据
     */
    private void initData() {
        hotelPriceDataList = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(HorizontalActivity.this));
        hotelPriceAdapter = new HotelPriceAdapter(HorizontalActivity.this, hotelPriceDataList);
        recyclerView.setAdapter(hotelPriceAdapter);
        hotelPriceAdapter.setOnItemClickListener(new HotelPriceAdapter.OnLastItemLister() {
            @Override
            public void onLastItem() {
                mHandler.sendEmptyMessage(20);
            }
        });

        imgList = new ArrayList<>();
        imgUrlList = new ArrayList<>();
        videoList = new ArrayList<>();
        lsDownFileName = new ArrayList<>();

        lsFullImg = new ArrayList<>();
        lsFullImgUrl = new ArrayList<>();
        lsFullVideoName = new ArrayList<>();
        fullScreenShowTime = new HashMap<>();

        lsfullScreenData = new ArrayList<>();
        lshalfScreenData = new ArrayList<>();
        if (!TextUtils.isEmpty(access_token)) {
            getNotices(); //获取公告语 滚动字幕
            getHotelprice(); //获取酒店房型以及价钱
            getMediafiles();  //获取半屏广告
            getFullScreenMediaFiles();//获取全屏广告
            getWeather();  //获取天气
        }
    }

    /**
     * 初始计时器
     */
    private void initRunnable() {
        runnable = new Runnable() {
            public void run() {
                handler.postDelayed(this, 1000);//延迟1秒钟
                //获取当前时间
                Date dateNow = new Date(System.currentTimeMillis());
                int h = dateNow.getHours();
                int m = dateNow.getMinutes();
                int s = dateNow.getSeconds();
                if (s % 10 == 0)
                    checkToken();//检查token
                if (h % 24 == 0 && m == 0 && s == 30)//凌晨12点 清除 视频图片
                    cleanData();// 清除缓存
                if (h % 1 == 0 && m == 0 && s == 10)//每1小时 刷新天气
                    getWeather();

                if (h == 0 && m == 0 && s < 2)
                    mHandler.sendEmptyMessage(501);//设置日期 星期 显示
                if (s == 0)
                    mHandler.sendEmptyMessage(500);//设置分钟显示
                if (m % 5 == 1 && s == 1)
                    getDataUpdate();  //心跳包  五分钟刷新一次数据
                if (m % 5 == 0 && s == 1)
                    getHotelprice();
                if (s % 5 == 0 && !recyclerView.canScrollVertically(1)) {
//                    LogUtils.e("LogUtils", "测试追加轮询数据" + "是否滑倒底部:" + !recyclerView.canScrollVertically(1));
                    //判断 是否滑倒底部
                    if (!recyclerView.canScrollVertically(1)) {
                        mHandler.sendEmptyMessage(20);
                    }
                }
            }
        };
        handler.postDelayed(runnable, 1000); // 开始Timer
    }

    /**
     * 释放缓存
     */
    public void cleanData() {
        Utils.deleteDir(getApplicationContext().getFilesDir().getAbsolutePath()); //视频清空
        Utils.deleteDir(getApplicationContext().getFilesDir().getAbsolutePath() + "/image_cache");//图片删除
    }

    /**
     * 初始全屏定时播放任务
     */
    private void initMyTimeTask() {
        if (fullScreenShowTime == null || fullScreenShowTime.size() <= 0) return;
        if (myTimeTask != null) myTimeTask.stop();
        myTimeTask = new MyTimeTask(1000,
                new TimerTask() {
                    @Override
                    public void run() {
                        //获取当前时间
                        Date dateNow = new Date(System.currentTimeMillis());
                        int h = dateNow.getHours();
                        int m = dateNow.getMinutes();
                        int s = dateNow.getSeconds();
                        String str = h + ":" + m;
                        if (fullScreenShowTime.containsKey(str) && s == 1) {
                            Bundle bundle = new Bundle();
                            bundle.putString("showTimeName", new Gson().toJson(fullScreenShowTime.get(str)));
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 41;
                            mHandler.sendMessage(message);
                        }
                    }
                });
        myTimeTask.start();
    }

    //获取全屏显示时间类型
    private Map<String, Integer> getShowTimeType() {
        //统计定点全屏显示 时间类型 时长
        Map<String, Integer> fullScreenType = new HashMap<>();
        for (MediafileBean etyBean : lsfullScreenData) {
            int num = etyBean.getDisplayDuration();//显示时长
            //显示的
            for (String showTypeName : etyBean.getArrDisplayTime()) {
                if (fullScreenType.containsKey(showTypeName)) {
                    Integer showTypeNum = fullScreenType.get(showTypeName);
                    showTypeNum = showTypeNum == null ? 0 : showTypeNum + num;
                    fullScreenType.put(showTypeName, showTypeNum);
                } else {
                    fullScreenType.put(showTypeName, num);
                }
            }
        }
        return fullScreenType;
    }

    /**
     * 初始全屏数据
     */
    private void initFullScreenData() {
//        LogUtils.e("fullScreenShowTime", "全屏屏展示" + "lsfullScreenData:" + new Gson().toJson(lsfullScreenData));
        if (lsfullScreenData == null || lsfullScreenData.size() <= 0) return;
        lsFullImg.clear();
        lsFullImgUrl.clear();
        lsFullVideoName.clear();

        String tempUrl;
        String printTxtPath = getApplicationContext().getFilesDir().getAbsolutePath();
        MediafileBean tempBean;//

        Map<String, FullScreenBean> tempMap = new HashMap<>();
        FullScreenBean tempfullScreenBean;
        ImagesBean tempImagesBean;
        String tempVideoName;

        for (int i = 0; i < lsfullScreenData.size(); i++) {
            tempImagesBean = null;
            tempVideoName = null;
            tempBean = lsfullScreenData.get(i);
            tempUrl = tempBean.getFileUrl() + "";
            if (!tempUrl.endsWith(".mp4")) {
                tempImagesBean = new ImagesBean(tempUrl);
                lsFullImg.add(tempImagesBean);
                lsFullImgUrl.add(tempUrl);
            } else {
                //判断视频信息
                tempVideoName = DownloadUtil.getUrlLastNameSuffix(tempUrl);
                if (!FileUtil.isFileExist(printTxtPath + "/" + tempVideoName)) {//文件是否存在
                    String finalTempUrl = tempUrl;
                    String finalTempVideoName = tempVideoName;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            downFile(finalTempUrl, printTxtPath, finalTempVideoName, 1); //下载
                        }
                    }).start();
                } else {
                    lsFullVideoName.add(tempVideoName);//已存在
                }
            }

            //先统时间段显示
            for (String time : tempBean.getArrDisplayTime()) {
                // 1.判断是否已存在播放点
                if (tempMap.containsKey(time))
                    tempfullScreenBean = tempMap.get(time);
                else {
                    tempfullScreenBean = new FullScreenBean();
                    tempfullScreenBean.setLsImage(new ArrayList<>());
                    tempfullScreenBean.setLsVideoName(new ArrayList<>());
                }

                //2.时间点 添加数据
                if (tempImagesBean != null) { //全屏图片
                    if (!tempfullScreenBean.getLsImage().contains(tempImagesBean))
                        tempfullScreenBean.getLsImage().add(tempImagesBean);
                }

                if (tempVideoName != null) { //全屏视频名
                    if (!tempfullScreenBean.getLsVideoName().contains(tempVideoName))
                        tempfullScreenBean.getLsVideoName().add(tempVideoName);
//                    //测试添加 zhangl 多加个视频
//                    if (time.equals("15:42"))
//                        tempfullScreenBean.getLsVideoName().add("vv20220907.mp4");
                }
                //3.将数据添加到map
                tempMap.put(time, tempfullScreenBean);
            }
        }

        fullScreenShowTime = tempMap;
//        LogUtils.e("fullScreenShowTime", "全屏屏展示" + "=====" + new Gson().toJson(fullScreenShowTime));
        initMyTimeTask();
    }

    //半屏展示
    private void showHalfScreenData() {
//        LogUtils.d("handlerTimer", "半屏展示");
        rl_left.setVisibility(View.VISIBLE);
        if (lshalfScreenData != null && lshalfScreenData.size() > 0) {
            imgList.clear();
            imgUrlList.clear();
            videoList.clear();
            lsDownFileName.clear();
            String tempUrl;
            String printTxtPath = getApplicationContext().getFilesDir().getAbsolutePath();
//            LogUtils.e("视频保存地址", "==" + printTxtPath);
            for (int i = 0; i < lshalfScreenData.size(); i++) {
                tempUrl = lshalfScreenData.get(i).getFileUrl() + "";
                if (!tempUrl.endsWith(".mp4")) {  //图片
                    imgList.add(new ImagesBean(tempUrl));
                    imgUrlList.add(tempUrl);
                } else {
                    videoList.add(tempUrl);
                    //判断视频信息
                    String downFielName = DownloadUtil.getUrlLastNameSuffix(tempUrl);
                    if (!FileUtil.isFileExist(printTxtPath + "/" + downFielName)) {//文件是否存在
                        String finalTempUrl = tempUrl;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                downFile(finalTempUrl, printTxtPath, downFielName, 0); //下载
                            }
                        }).start();
                    } else {
                        lsDownFileName.add(downFielName);//已存在
                    }
                }
            }

            mHandler.sendEmptyMessage(98);//判断是否需要下载图片

            //加载 轮播图或视频
            showBannerOrVideo(imgList, imgUrlList, videoList);
        }
    }

    /**
     * 文件下载 url：地址 filepateh： 存放文件路径  filename: 文件名字
     *
     * @param url       地址
     * @param filepath  存放文件路径
     * @param filename  文件名字
     * @param videoType 视频类型 0 半屏 1全屏  2图片
     */
    private void downFile(String url, String filepath, String filename, int videoType) {
        DownloadUtil.get().download(url, filepath, filename,
                new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        if (videoType == 0) {
                            if (!lsDownFileName.contains(filename))
                                lsDownFileName.add(filename);
                        }
                        if (videoType == 1) {
                            if (!lsFullVideoName.contains(filename))
                                lsFullVideoName.add(filename);
                        }
                        if (videoType == 2) {
                            //传递的数据
                            Bundle bundle = new Bundle();
                            bundle.putString("imageName", filename);
                            //发送数据
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 99;
                            mHandler.sendMessage(message);
//                            lsDownloadIamge.add(filename);//图片下载成功
                            //判断当前图片的idex 位置
//                           imgUrlList.indexOf(filename)

                        }
                        //下载成功
//                        LogUtils.i(TAG, "onDownloadSuccess:....... ..................文件下载成功..............................");
                    }

                    @Override
                    public void onDownloading(int progress) {
                        //下载中
//                        LogUtils.i(TAG, "onDownloading:..............................文件下载中......" + filename + "..........................");
                    }

                    @Override
                    public void onDownloadFailed(Exception e) {
                        //下载异常进行相关提示操作
//                        LogUtils.e(TAG, "onDownloadFailed:..........................下载文件失败..............................." + e.getMessage());
                    }
                });
    }

    /**
     * 显示 轮播图 或视频
     *
     * @param lsImg      轮播图
     * @param lsUrl      轮播图Url
     * @param lsVideoUrl 视频url
     */
    private void showBannerOrVideo(final List<ImagesBean> lsImg, final List<String> lsUrl, List<String> lsVideoUrl) {
        if (imgList != null && imgList.size() > 0) {
            loadBanner(lsImg, lsUrl, lsVideoUrl);
        } else {
            playVideo(lsImg, lsUrl);//播放视频_半屏
        }
    }

    /**
     * 加载 播放轮播图 imgUrlList
     */
    private void loadBanner(final List<ImagesBean> lsImg, final List<String> lsUrl, final List<String> lsVideoUrl) {
        if ((lsImg == null || lsImg.size() == 0) && (lsVideoUrl == null || lsVideoUrl.size() == 0))
            return;
//        LogUtils.e("loadBanner", new Gson().toJson(lsUrl));
        if (lsImg != null && lsImg.size() > 0) {
            mXBanner.setVisibility(View.VISIBLE);
            //代码设置框架占位图，也可在布局中设置
            mXBanner.setBannerPlaceholderImg(R.mipmap.default_image, ImageView.ScaleType.FIT_XY);
            video_view_right.setVisibility(View.GONE);
            //加载广告图片
            mXBanner.loadImage(new XBanner.XBannerAdapter() {
                @Override
                public void loadBanner(XBanner banner, Object model, View view, int position) {
                    ImageView imageView = (ImageView) view;
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    String imgName = DownloadUtil.getUrlLastNameSuffix(lsUrl.get(position));
                    if (lsDownloadIamge.contains(imgName)) {
                        //本地
                        Glide.with(HorizontalActivity.this)
                                .load(new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/image_cache/" + imgName))
                                .placeholder(R.mipmap.default_image)
                                .into(imageView);
                    } else {
                        Glide.with(HorizontalActivity.this)
                                .load(lsUrl.get(position))
                                .placeholder(R.mipmap.default_image)
                                .into(imageView);
                    }
                }
            });
            final int[] index = {0};
            //轮播图 滚动 监听事件
            mXBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                }

                @Override
                public void onPageSelected(int position) {
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                    if (state == 2) {  //当滑动完毕的时候
                        index[0] = index[0] + 1;
                        if (index[0] > lsUrl.size()) {
                            playVideo(lsImg, lsUrl);//播放视频_半屏
                        }
                    }
                }
            });

            //添加轮播图片数据
            mXBanner.setBannerData(R.layout.layout_fresco_homebanner, lsImg);

        } else {
            playVideo(lsImg, lsUrl);//播放视频_半屏
        }
    }

    /**
     * 加载 播放视频
     */
    private void playVideo(final List<ImagesBean> lsImg, final List<String> lsUrl) {
        if (lsDownFileName != null && lsDownFileName.size() > 0) {
            //设置播放视频
            String absolutePath = getApplicationContext().getFilesDir().getAbsolutePath() + "/";
            //播放视频  半屏
            mXBanner.setVisibility(View.GONE);
            video_view_right.setVisibility(View.VISIBLE);
            currentPosition = 0;
            //监听视频资源装载完成
            video_view_right.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    video_view_right.start();//开始播放视频
//                    video_view_right.setVideoScalingMode();
                }
            });
            //监听视频播放完成
            video_view_right.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    video_view_right.stopPlayback();
                    currentPosition++;
                    //判断视频数量
                    if (currentPosition <= lsDownFileName.size() - 1) {
                        try {
                            //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径3" + uri);
                            String uri = absolutePath + lsDownFileName.get(currentPosition);
                            if (!TextUtils.isEmpty(uri)) {
                                video_view_right.setVideoURI(Uri.parse(uri));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (lsImg != null && lsImg.size() > 0)
                            loadBanner(imgList, lsUrl, null);//播放图片
                    }
                }
            });
            //监听视频播放出错
            video_view_right.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    stopPlaybackVideo();

                    //当前视频播放异常 播放下个
                    currentPosition++;
                    //判断视频数量
                    if (currentPosition <= lsDownFileName.size() - 1) {
                        try {
                            //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径3" + uri);
                            String uri = absolutePath + lsDownFileName.get(currentPosition);
                            if (!TextUtils.isEmpty(uri)) {
                                video_view_right.setVideoURI(Uri.parse(uri));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (lsImg != null && lsImg.size() > 0)
                            loadBanner(imgList, lsUrl, null);//播放图片
                    }
                    return true;
                }
            });

            try {
                video_view_right.stopPlayback();
                //播放已经下载好的视频 LogUtils.d(TAG, "本地视频路径4" + uri);
                String uri = absolutePath + lsDownFileName.get(currentPosition);
                if (!TextUtils.isEmpty(uri)) {
                    video_view_right.setVideoURI(Uri.parse(uri));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if (lsImg != null && lsImg.size() > 0)
                loadBanner(lsImg, lsUrl, null);//播放图片   没有视频直接播放图片
        }
    }

    private Runnable runnable;
    private Handler handler = new Handler();

    /**
     * 检查token是否过期
     */
    public boolean checkToken() {
        boolean rs = false;
        tokenBean = CacheUtil.getTokenCache(this);
        if (tokenBean != null && tokenBean.isNoExpire()) {
            access_token = tokenBean.getAccess_token();
            rs = true;
        } else if (tokenBean != null) {
            refreshToken(tokenBean.getRefresh_token());//刷新可用  刷新token
        } else {
            getLoginToken();//重新登录
        }
        return rs;
    }

    /**
     * 刷新token
     */
    private void refreshToken(String refresh_token) {
//        LogUtils.e("tokenBean", "刷新token：开始" + new Gson().toJson(tokenBean));
        HashMap<String, String> refreshMap = new HashMap<>();
        refreshMap.put("grant_type", "refresh_token");
        refreshMap.put("refresh_token", refresh_token);
        TokenBeanParser<TokenBean> responseBeanParser = new TokenBeanParser<TokenBean>(new TypeToken<TokenBean>() {
        }.getType());
        ApiService.getInstance().get(Api.ACCESS_TOKEN, refreshMap, responseBeanParser, new ApiContract.OnResponseListener<TokenBean>() {
            @Override
            public void onSuccess(ResponseBean<TokenBean> result) {
                if (result.isSuccess()) {//登录成功
                    CacheUtil.setTokenCache(HorizontalActivity.this, result.getData());//保存token
                    tokenBean = result.getData();
                    access_token = tokenBean.getAccess_token();
                } else {
                    //刷新token失败
                    mHandler.sendEmptyMessage(110);
                }
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
//                LogUtils.e("refreshToken ", "刷新token异常 onError:" + error.getErrorMessage());
                //发送数据
                mHandler.sendEmptyMessage(110);
            }
        });
    }

    /**
     * 重新获取登录token
     */
    private void getLoginToken() {
//        LogUtils.e("tokenBean", "重新获取登录token：");
        String client_id = CacheUtil.getCache(HorizontalActivity.this).getString("client_id", "");
        String client_secret = CacheUtil.getCache(HorizontalActivity.this).getString("client_secret", "");
        String versionName = Utils.getVersionName(HorizontalActivity.this);
        String deviceId = Utils.getDeviceId(HorizontalActivity.this);
        String currentapiVersion = "android_" + Build.VERSION.RELEASE;
        HashMap<String, String> reqMap = new HashMap<>();
        reqMap.put("device_id", deviceId);
        reqMap.put("os_version", currentapiVersion);
        reqMap.put("version", versionName);
        reqMap.put("grant_type", "client_credentials");
        reqMap.put("client_id", client_id);
        reqMap.put("client_secret", client_secret);
        reqMap.put("screentype", CacheUtil.getCache(this).getString("screenType", "across").equals("across") ? "H" : "V");

        TokenBeanParser<TokenBean> responseBeanParser = new TokenBeanParser<TokenBean>(new TypeToken<TokenBean>() {
        }.getType());
        ApiService.getInstance().get(Api.ACCESS_TOKEN, reqMap, responseBeanParser, new ApiContract.OnResponseListener<TokenBean>() {

            @Override
            public void onSuccess(ResponseBean<TokenBean> result) {
                if (result.isSuccess()) {//登录成功
                    CacheUtil.setTokenCache(HorizontalActivity.this, result.getData());//保存token
                    CacheUtil.getCache(HorizontalActivity.this).put("client_id", client_id);
                    CacheUtil.getCache(HorizontalActivity.this).put("client_secret", client_secret);
                    tokenBean = result.getData();
                    access_token = tokenBean.getAccess_token();
                } else {
                    //发送数据
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", "登录身份失效!" + result.getError_description());
                    Message message = Message.obtain();
                    message.setData(bundle);   //message.obj=bundle  传值也行
                    message.what = 120;
                    mHandler.sendMessage(message);
                }
            }

            @Override   //登录失败
            public void onError(ApiError error) {
                //发送数据
                Bundle bundle = new Bundle();
                bundle.putString("msg", "登录身份异常!" + error.getErrorMessage());
                Message message = Message.obtain();
                message.setData(bundle);   //message.obj=bundle  传值也行
                message.what = 120;
                mHandler.sendMessage(message);
            }
        });
    }

    /**
     * 实时刷新数据
     */
    private void getDataUpdate() {
        ResponseBeanParser<UpdateBean> responseBeanParser = new ResponseBeanParser<UpdateBean>(new TypeToken<ResponseBean<UpdateBean>>() {
        }.getType());
        ApiService.getInstance().get(
                Api.Update_Data, access_token, responseBeanParser,
                new ApiContract.OnResponseListener<UpdateBean>() {
                    @Override
                    public void onSuccess(ResponseBean<UpdateBean> result) {
                        if (result != null && result.isSuccess() && result.getData() != null) {
                            String str = new Gson().toJson(result.getData());
                            //传递的数据
                            Bundle bundle = new Bundle();
                            bundle.putString("updateData", str);
                            //发送数据
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 6;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(ApiError error) {
                    }
                });
    }

    /**
     * 获取公告语
     */
    private void getNotices() {
        ResponseBeanParser<List<NoticeBean>> responseBeanParser = new ResponseBeanParser<List<NoticeBean>>(new TypeToken<ResponseBean<List<NoticeBean>>>() {
        }.getType());
        ApiService.getInstance().get(Api.Notices, access_token, responseBeanParser, new ApiContract.OnResponseListener<List<NoticeBean>>() {
            @Override
            public void onSuccess(ResponseBean<List<NoticeBean>> result) {
                if (result.isSuccess()) {//获取成功
                    if (!result.getData().isEmpty()) {
                        lsNoticeBean = result.getData();
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                }
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
                LogUtils.e("getNotices ", "获取公告语 onError:" + error.getErrorMessage());
            }
        });
    }

    /**
     * 获取酒店房价
     */
    private void getHotelprice() {
        ResponseBeanParser<List<HotelpriceBean>> responseBeanParser = new ResponseBeanParser<List<HotelpriceBean>>(new TypeToken<ResponseBean<List<HotelpriceBean>>>() {
        }.getType());
        ApiService.getInstance().get(Api.Hotel_Prices, access_token, responseBeanParser, new ApiContract.OnResponseListener<List<HotelpriceBean>>() {
            @Override
            public void onSuccess(ResponseBean<List<HotelpriceBean>> result) {
                if (result.isSuccess()) {//获取成功
                    if (result.getData() != null) {
                        tempPriceDataList = result.getData();
                        Message message = Message.obtain();
                        message.what = 2;
                        mHandler.sendMessage(message);
                    }
                }
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
                LogUtils.e("getHotelprice ", "获取房价 onError:" + error.getErrorMessage());
            }
        });
    }

    /**
     * 获取天气预报  .url("https://tianqiapi.com/api?version=v1&appid=32929963&appsecret=38JNKHHL")
     */
    private void getWeather() {
        ResponseBeanParser<List<WeatherCityBean>> responseBeanParser = new ResponseBeanParser<List<WeatherCityBean>>(new TypeToken<ResponseBean<List<WeatherCityBean>>>() {
        }.getType());
        ApiService.getInstance().get(Api.Weather, access_token, responseBeanParser, new ApiContract.OnResponseListener<List<WeatherCityBean>>() {
            @Override
            public void onSuccess(ResponseBean<List<WeatherCityBean>> result) {
//                LogUtils.e("GetWeather", llTodayList.size() + "===llTomList:" + llTomList.size() + "===" + new Gson().toJson(result));
                Message message = Message.obtain();
                if (result.isSuccess() && !result.getData().isEmpty()) {//获取天气预报成功
                    lsWeather = result.getData();
                    message.what = 8;
                } else {
                    message.what = -8;
                }
                mHandler.sendMessage(message);   //发送数据
            }

            @Override   //刷新token异常
            public void onError(ApiError error) {
                LogUtils.e("GetWeather ", "获取天气异常 onError:" + error.getErrorMessage());
                Message message = Message.obtain();
                message.what = -8;
                mHandler.sendMessage(message);   //发送数据
            }
        });
    }

    /**
     * 设置天气 图片
     */
    private void setWeather(String weather, ImageView ivTemp) {
        if (weather.contains("晴")) {
            ivTemp.setImageResource(R.mipmap.sun);
        } else if (weather.contains("多云")) {
            ivTemp.setImageResource(R.mipmap.duoyun);
        } else if (weather.contains("阴")) {
            ivTemp.setImageResource(R.mipmap.yin);
        } else if (weather.contains("小雨")) {
            ivTemp.setImageResource(R.mipmap.xiaoyu);
        } else if (weather.contains("中雨")) {
            ivTemp.setImageResource(R.mipmap.zhongyu);
        } else if (weather.contains("雷阵雨")) {
            ivTemp.setImageResource(R.mipmap.leizhenyu);
        } else if (weather.contains("阵雨")) {
            ivTemp.setImageResource(R.mipmap.zhenyu);
        } else if (weather.contains("大雨")) {
            ivTemp.setImageResource(R.mipmap.dayu);
        } else if (weather.contains("暴雨")) {
            ivTemp.setImageResource(R.mipmap.baoyu);
        } else if (weather.contains("大暴雨")) {
            ivTemp.setImageResource(R.mipmap.dabaoyu);
        } else if (weather.contains("冻雨")) {
            ivTemp.setImageResource(R.mipmap.dongyu);
        } else if (weather.contains("雾")) {
            ivTemp.setImageResource(R.mipmap.wu);
        } else if (weather.contains("轻雾")) {
            ivTemp.setImageResource(R.mipmap.qingwu);
        } else if (weather.contains("霾")) {
            ivTemp.setImageResource(R.mipmap.mai);
        } else if (weather.contains("冰雹")) {
            ivTemp.setImageResource(R.mipmap.bingbao);
        } else if (weather.contains("浮尘")) {
            ivTemp.setImageResource(R.mipmap.fuchen);
        } else if (weather.contains("沙尘暴")) {
            ivTemp.setImageResource(R.mipmap.shachenbao);
        } else if (weather.contains("扬沙")) {
            ivTemp.setImageResource(R.mipmap.yangsha);
        } else if (weather.contains("小雪")) {
            ivTemp.setImageResource(R.mipmap.xiaoyu);
        } else if (weather.contains("中雪")) {
            ivTemp.setImageResource(R.mipmap.zhongxue);
        } else if (weather.contains("大雪")) {
            ivTemp.setImageResource(R.mipmap.daxue);
        } else if (weather.contains("阵雪")) {
            ivTemp.setImageResource(R.mipmap.zhenxue);
        } else if (weather.contains("雨夹雪")) {
            ivTemp.setImageResource(R.mipmap.yujiaxue);
        } else if (weather.contains("暴雪")) {
            ivTemp.setImageResource(R.mipmap.baoxue);
        }
    }

    /**
     * 获取酒店  图片 和  视频(半屏) 数据获取
     */
    private void getMediafiles() {
        ResponseBeanParser<List<MediafileBean>> responseBeanParser = new ResponseBeanParser<List<MediafileBean>>(new TypeToken<ResponseBean<List<MediafileBean>>>() {
        }.getType());
        ApiService.getInstance().get(
                Api.Media_Files, access_token, responseBeanParser,
                new ApiContract.OnResponseListener<List<MediafileBean>>() {
                    @Override
                    public void onSuccess(ResponseBean<List<MediafileBean>> result) {
                        if (result != null && result.isSuccess() && result.getData() != null && result.getData().size() > 0) {
                            String str = new Gson().toJson(result.getData());
                            //传递的数据
                            Bundle bundle = new Bundle();
                            bundle.putString("Mediafiles", str);
                            //发送数据
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 7;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(ApiError error) {
                    }
                });
    }

    /**
     * 获取酒店  图片 和  视频(全屏)
     */
    private void getFullScreenMediaFiles() {
        ResponseBeanParser<List<MediafileBean>> responseBeanParser = new ResponseBeanParser<List<MediafileBean>>(new TypeToken<ResponseBean<List<MediafileBean>>>() {
        }.getType());
        ApiService.getInstance().get(
                Api.Full_Screen_Media_Files, access_token, responseBeanParser,
                new ApiContract.OnResponseListener<List<MediafileBean>>() {
                    @Override
                    public void onSuccess(ResponseBean<List<MediafileBean>> result) {
                        if (result != null && result.isSuccess() && result.getData() != null && result.getData().size() > 0) {
                            String str = new Gson().toJson(result.getData());
                            //传递的数据
                            Bundle bundle = new Bundle();
                            bundle.putString("FullScreenMediaFiles", str);
                            //发送数据
                            Message message = Message.obtain();
                            message.setData(bundle);   //message.obj=bundle  传值也行
                            message.what = 9;
                            mHandler.sendMessage(message);
                        }
                    }

                    @Override
                    public void onError(ApiError error) {
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!video_view_right.isPlaying()) {
            video_view_right.resume();//将视频从头开始播放
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (video_view_right.canPause()) {
            video_view_right.pause();//暂停播放视频
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlaybackVideo();
        handler.removeCallbacks(runnable); //停止Timer
        handler.removeCallbacksAndMessages(null);
        mHandler.removeCallbacksAndMessages(null);
        if (myTimeTask != null) {
            myTimeTask.stop();
        }
    }

    private void stopPlaybackVideo() {
        try {
            video_view_right.stopPlayback();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
